package algorithm.search.binarysearch;

import static org.junit.Assert.*;
import java.util.Random;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import algorithm.search.binarysearch.interfaces.ISearch;

public class BinarySearcherTest {

	@Before
	public void setUp() throws Exception {
	}

	@After
	public void tearDown() throws Exception {
	}

	@Test
	public void testSearchInsideElement() {
		int len = 1000;
        int sparseFactor = 3;
        int testTimes = 40;
        ISearch<Integer> searcher = new BinarySearcher<Integer>();
        NormalSearcher<Integer> checker = new NormalSearcher<Integer>();
        boolean success = true;
        for(int i=0;i<testTimes;i++){
            Integer[] testCase = generateTestCase(len,sparseFactor);
            for (int j=0;j<len;j++){
                int result = searcher.search(testCase,testCase[j]);
                int[] expectResult = checker.searchAll(testCase,testCase[j]);
                Integer[] tempArr = new Integer[expectResult.length];
                for(int k=0;k<expectResult.length;k++)
                    tempArr[k] = expectResult[k];
                if(checker.search(tempArr,result)<0){
                    success = false;
                    break;
                }
            }
            if(!success)
            	break;
        }
        assertTrue(success);
	}
	
	@Test
	public void testSearchOutsideElement() {
		int len = 1000;
        int sparseFactor = 3;
        Integer foreigner = -1;
        int testTimes = 40;
        ISearch<Integer> searcher = new BinarySearcher<Integer>();
        NormalSearcher<Integer> checker = new NormalSearcher<Integer>();
        boolean success = true;
        for(int i=0;i<testTimes;i++){
            Integer[] testCase = generateTestCase(len,sparseFactor);
            for (int j=0;j<len;j++){
                int result = searcher.search(testCase,foreigner);
                if(result!=-1){
                	success = false;
                    break;
                }
            }
            if(!success)
            	break;
        }
        assertTrue(success);
	}
	
	private static Integer[] generateTestCase(int len, int sparseFactor){
        Integer[] arr = new Integer[len];
        for(int i=0;i<len;i++){
            arr[i] = new Integer(ran.nextInt(len * sparseFactor));
        }
        return arr;
    }
	
	private static Random ran = new Random();

}
